<template>
	<div class="container">
    <h2>用户登录</h2>

    <el-form ref="formRef" class="form-container" :model="form" :rules="formRules">
      <el-form-item prop="username">
        <el-input type="text" prefix-icon="el-icon-user" v-model.trim="form.username" placeholder="请输入账号"></el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input type="password" prefix-icon="el-icon-lock" v-model.trim="form.password" placeholder="请输入账号"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button class="submit-btn" type="primary" native-type="submit" @click="submitForm">登录</el-button>
      </el-form-item>
    </el-form>
	</div>
</template>

<script>
// todo: js-base64 v3.x 版本不支持 IE 浏览器，需要降低版本至 2.x
import { Base64 } from 'js-base64';

export default {
  data() {
    return {
      form: {
        username: 'jczx',
        password: '123456',
      },
      formRules: {
        username: [{ required: true, message: '账户不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
      },
    };
  },

  methods: {
    submitForm(){
      this.$refs['formRef'].validate(valid => {
        if (!valid) {
          this.$message.warning('邮箱和密码不能为空!');
          return;
        }
        const formData = new FormData();
        formData.append('loginName', Base64.encode(this.form.username)); // 用户名
        formData.append('passWord', Base64.encode(this.form.password)); // 密码
        this.$store.dispatch('user/login', formData).then(() => {
          this.$message.success('登录成功');
          const currentRoute = this.$router.currentRoute;
          if (currentRoute && currentRoute.query && currentRoute.query.redirect) {
            this.$router.push(currentRoute.query.redirect || '/home');
          } else {
            this.$router.push('/home');
          }
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		left: 50%;
		top: 40%;
		transform: translate(-50%, -50%);
		border: 1px solid #ddd;
		background-color: #fff;
		padding: 24px 32px;
    box-shadow: 0 3px 6px -1px rgba(0, 0, 0, 0.19);
    border-radius: 4px;

    h2 {
      text-align: center;
    }
	}

	.form-container {
		width: 320px;
		margin: 0 auto;
	}

	.submit-btn {
    width: 100%;
    height: 48px;
	}
</style>
